package algorithm.graph;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class DenseGraph implements Graph {

    //节点个数
    private int n;
    //边的个数
    private int m;
    //是否为有向图
    private boolean directed;

    private boolean[][] g;

    public DenseGraph(int count,boolean directed){
        this.directed = directed;
        this.n = count;
        this.g = new boolean[count][count];
        //构造函数初始化，每一个值为false
        for (int i = 0; i < g.length; i++) {
            for (int j = 0; j < g[i].length; j++) {
                g[i][j] = false;
            }
        }
    }

    @Override
    public int V() {
        return n;
    }

    @Override
    public int E() {
        return m;
    }

    @Override
    public void addEdge(int v, int w) {
        assert v >= 0 && v < n ;
        assert w >= 0 && w < n ;
        if (g[v][w]){
            return;
        }
        g[v][w]=true;
        if (!directed){
            g[w][v]=true;
        }
        m++;
    }

    @Override
    public boolean hasEdge(int v, int w) {
        return g[v][w];
    }

    @Override
    public void show() {
        for (boolean[] booleans : g) {
            for (boolean aBoolean : booleans) {
                System.out.print((aBoolean?1:0)+"\t");
            }
            System.out.println("");
        }
    }

    @Override
    public Iterator<Integer> iterator(int v) {
        boolean[] booleans = g[v];
        List<Integer> iter = new LinkedList<>();
        for (int i = 0; i < booleans.length; i++) {
            if (booleans[i]){
                iter.add(i);
            }
        }
        return iter.iterator();
    }
}
